package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SystemUserMapper systemUserMapper;
    //private StringRedisTemplate StringRedisTemplate;

    private final RedisTemplate<String,String> redisTemplate;

    public LoginServiceImpl(@Qualifier("redisTemplate") RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public CaptchaVo getCaptcha() {
        /*参数的意思是生成的图片宽130px,高48,验证码的长度 */
        SpecCaptcha specCaptcha = new SpecCaptcha(130,48,4);
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
        //获取验证码的文本内容
        String code = specCaptcha.text().toLowerCase();
        String key = RedisConstant.ADMIN_LOGIN_PREFIX+ UUID.randomUUID().toString().replace("-","");
        String imageUrl = specCaptcha.toBase64();
        redisTemplate.opsForValue().set(key,code,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);

        return new CaptchaVo(imageUrl,key);
    }

    @Override
    public String login(LoginVo loginVo) {
        //- 判断captchaCode是否为空，若为空，则直接响应验证码为空；若不为空进行下一步判断。
        String captchaCode = loginVo.getCaptchaCode();
        if (ObjectUtils.isEmpty(captchaCode)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        //- 根据captchaKey从Redis中查询之前保存的code，若查询出来的code为空，则直接响应验证码已过期；若不为空进行下一步判断。
        String captchaKey = loginVo.getCaptchaKey();
        String code = (String) redisTemplate.opsForValue().get(captchaKey);
        if (ObjectUtils.isEmpty(code)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //- 比较captchaCode和code，若不相同，则直接响应验证码不正确；若相同则进行下一步判断。
        if (!code.equalsIgnoreCase(captchaCode)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //- 验证码使用过后就在redis中删除
        //redisTemplate.delete(captchaKey);
        //- 根据username查询数据库，若查询结果为空，则直接响应账号不存在；若不为空则进行下一步判断。
        LambdaQueryWrapper<SystemUser> userLambdaQueryWrapper=new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(SystemUser::getUsername,loginVo.getUsername());
        SystemUser systemUser=systemUserMapper.selectOne(userLambdaQueryWrapper);
        if (ObjectUtils.isEmpty(systemUser)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //- 查看用户状态，判断是否被禁用，若禁用，则直接响应账号被禁；若未被禁用，则进行下一步判断。
        if (systemUser.getStatus().getCode().equals(0)){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //- 比对password和数据库中查询的密码，若不一致，则直接响应账号或密码错误，若一致则进行入最后一步。
        if (!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //- 创建JWT，并响应给浏览器。
        String token = JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
        return token;
    }
}
